package com.soft.line.filter;

import com.soft.line.auth.AuthConstant;
import com.soft.line.auth.Md5Util;
import com.soft.line.entity.UserInfo;
import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

/**
 * @author wu.xueqiao on 2020/5/12.
 * @version 0.1
 */
public class Token {

    private String account;

    private String username;



    private int err = 0;

    public static final int ExpiredJwtError = 1;

    public static final int SignatureError = 2;

    public Token(final String token) {
        try {
//            if (StringUtils.isEmpty(token) || token.length() < AuthConstant.TOKEN_MD5_LENGTH) {
//                return null;
//            }
            String base64Token = token.substring(0, token.length() - AuthConstant.TOKEN_MD5_LENGTH);
//            if (!token.toUpperCase().endsWith(Md5Util.encodeMd5(base64Token + AuthConstant.SAFE_STRING).toUpperCase())) {
//                return null;
//            }
            String tokenPlainText = new String(Base64.decodeBase64(base64Token));
            tokenPlainText = tokenPlainText.substring(AuthConstant.USER_TOKEN_PREFIX.length());
            String[] arr = tokenPlainText.split("-");
//            if (arr.length < 4 - 1) {
//                return null;
//            }

//            UserToken userToken = new UserToken();
            UserInfo user = new UserInfo();
            user.setId(Integer.valueOf(arr[0]));
            user.setUserName(arr[1]);

            this.username = arr[1];
        } catch (final ExpiredJwtException e) {
            this.err = ExpiredJwtError;
        } catch (final SignatureException e) {
            this.err = SignatureError;
        }
    }

    public String getAccount() {

        return account;
    }


    public String getUsername() {

        return username;
    }


    public int getErr() {

        return err;
    }

}
